<template>
  <div class="contract-add-page">
    <div class="title-area top-fixed">
      <van-nav-bar
        title="创建客户"
        left-text=""
        right-text=""
        left-arrow
        @click-left="onClickLeft"
      />
    </div>
    <div class="more-form-area">
      <van-form @submit="onSubmit" round="6px" input-align="right">
        <div class="base-info-form form-pub">
          <van-field
            v-model="formData.companyName"
            name="客户名称"
            label="客户名称"
            placeholder="客户名称"
            :rules="[{ required: true, message: '请填写客户名称' }]"
            required
          />
          <!-- 客户来源 -->
          <van-field
            v-model="customerSourceName"
            name="客户来源"
            label="客户来源"
            placeholder="请选择"
            :rules="[{ required: true, message: '请选择客户来源' }]"
            right-icon="arrow-down"
            readonly
            required
            @click="handleDrop(1)"
          />
          <van-radio-group
            v-model="formData.customerSource"
            style="
              border: 1px solid #3875fb;
              border-radius: 6px;
              background-color: #fff;
              overflow: hidden;
            "
            @change="handleChangeGroup(1)"
            v-if="showGroupList1"
          >
            <van-cell-group>
              <van-cell
                v-for="option in dict_datas.customer_source"
                :key="option.value"
                :title="option.label"
                clickable
              >
                <template #right-icon>
                  <van-radio :name="option.value" />
                </template>
              </van-cell>
            </van-cell-group>
          </van-radio-group>
          <!-- 客户来源 end -->
          <!-- 归属人 -->
          <van-field
            v-model="applicantName"
            :disabled="isSalesStaff"
            name="归属人"
            label="归属人"
            placeholder="请选择"
            :rules="[{ required: true, message: '请选择归属人' }]"
            right-icon="arrow-down"
            readonly
            required
            @click="handleDrop(2)"
          />
          <van-radio-group
            v-model="formData.applicant"
            style="
              border: 1px solid #3875fb;
              border-radius: 6px;
              background-color: #fff;
              overflow: hidden;
            "
            @change="handleChangeGroup(2)"
            v-if="showGroupList2"
          >
            <van-cell-group>
              <van-cell
                v-for="ite in userOptions"
                :key="parseInt(ite.id)"
                :title="ite.nickname"
                clickable
              >
                <template #right-icon>
                  <van-radio :name="parseInt(ite.id)" />
                </template>
              </van-cell>
            </van-cell-group>
          </van-radio-group>
          <!-- 归属人 end -->
          <!-- 是否有效 -->
          <van-field
            v-model="isValidName"
            name="是否有效"
            label="是否有效"
            placeholder="请选择"
            :rules="[{ required: true, message: '请选择是否有效' }]"
            right-icon="arrow-down"
            readonly
            required
            @click="handleDrop(3)"
          />
          <van-radio-group
            v-model="formData.isValid"
            style="
              border: 1px solid #3875fb;
              border-radius: 6px;
              background-color: #fff;
              overflow: hidden;
            "
            @change="handleChangeGroup(3)"
            v-if="showGroupList3"
          >
            <van-cell-group>
              <van-cell
                v-for="option in getDictDatas(DICT_TYPE.CUSTOMER_STATUS)"
                :key="option.value"
                :title="option.label"
                clickable
              >
                <template #right-icon>
                  <van-radio :name="option.value" />
                </template>
              </van-cell>
            </van-cell-group>
          </van-radio-group>
          <!-- 是否有效 end -->
          <van-field
            name="客户星级"
            label="客户星级"
            :rules="[{ required: true, message: '请选择客户星级' }]"
            required
          >
            <template #input>
              <van-rate v-model="formData.customerRating" color="#3875f6" />
            </template>
          </van-field>
          <!-- 跟进阶段 -->
          <van-field
            v-model="followUpStageName"
            name="跟进阶段"
            label="跟进阶段"
            placeholder="请选择"
            :rules="[{ required: true, message: '请选择跟进阶段' }]"
            right-icon="arrow-down"
            readonly
            required
            @click="handleDrop(4)"
          />
          <van-radio-group
            v-model="formData.followUpStage"
            style="
              border: 1px solid #3875fb;
              border-radius: 6px;
              background-color: #fff;
              overflow: hidden;
            "
            @change="handleChangeGroup(4)"
            v-if="showGroupList4"
          >
            <van-cell-group>
              <van-cell
                v-for="option in dict_datas.follow_up_stage"
                :key="Number(option.value)"
                :title="option.label"
                clickable
              >
                <template #right-icon>
                  <van-radio :name="option.value" />
                </template>
              </van-cell>
            </van-cell-group>
          </van-radio-group>
          <!-- 跟进阶段 end -->
          <!-- 地区 -->
          <van-field
            readonly
            clickable
            name="area"
            :value="value"
            label="所在地区"
            placeholder="点击选择省市区"
            :rules="[{ required: true, message: '请选择所在地区' }]"
            @click="showArea = true"
          />
          <van-popup v-model="showArea" position="bottom">
            <van-area
              :area-list="areaList"
              @confirm="onConfirm"
              @cancel="showArea = false"
            />
          </van-popup>
          <!-- 地区 end -->
          <van-field
            v-model="formData.address"
            name="详细地址"
            label="详细地址"
            placeholder="详细地址"
          />
          <!-- 联系人 -->
          <div class="pub-box pro-list-box">
            <div class="pub-hd up-hd">
              <span class="pub-tit pro-tit"
                ><span class="req">*</span>联系人信息</span
              >
              <div class="oop-ara">
                <span class="b1" @click="addContact" style="display: block"
                  >添加</span
                >
              </div>
            </div>
            <van-divider style="margin: 0" />
            <div class="pub-bd pro-bd">
              <div class="contact-area">
                <div
                  class="contract-item"
                  v-for="(item, index) in formData.contactList"
                  :key="index"
                >
                  <van-field
                    v-model="item.contactName"
                    name="联系人姓名"
                    label="联系人姓名"
                    placeholder="联系人姓名"
                    :rules="[{ required: true, message: '请填写联系人姓名' }]"
                    required
                  >
                    <template #button>
                      <van-switch
                        v-model="item.preferredFlag"
                        size="24px"
                        style="vertical-align: middle"
                        @change="
                          (val) => changeContactPreferredFlag(val, index)
                        "
                      />
                      <span style="margin: 0 0 0 4px">首选</span>
                    </template>
                  </van-field>
                  <van-field
                    v-model="item.contactMobile"
                    name="手机"
                    label="手机"
                    placeholder="手机"
                    :rules="[{ validator, message: '请输入正确的手机格式' }]"
                    required
                  />
                  <van-field
                    v-model="item.contactWx"
                    name="微信"
                    label="微信"
                    placeholder="微信"
                  />
                  <van-field
                    v-model="item.contactTel"
                    name="电话"
                    label="电话"
                    placeholder="电话"
                  />
                  <van-field
                    v-model="item.contactEmail"
                    name="电子邮箱"
                    label="电子邮箱"
                    placeholder="电子邮箱"
                  />
                  <van-field
                    v-model="item.contactDepart"
                    name="部门"
                    label="部门"
                    placeholder="部门"
                  />
                  <van-field
                    v-model="item.contactPost"
                    name="职务"
                    label="职务"
                    placeholder="职务"
                  />
                  <van-field
                    v-model="item.remark"
                    rows="2"
                    autosize
                    label="备注信息"
                    type="textarea"
                    maxlength="50"
                    placeholder="请输入备注信息"
                    show-word-limit
                  />
                </div>
              </div>
            </div>
          </div>
          <!-- 联系人 end -->
        </div>
        <div class="more-info-form form-pub" style="margin: 12px 0 60px 0">
          <van-field
            v-model="formData.remark"
            rows="2"
            autosize
            label="备注信息"
            type="textarea"
            maxlength="50"
            placeholder="请输入"
            show-word-limit
          />
        </div>
        <div class="btm-area pub-btm-area">
          <span class="btn-reset" @click="cancel">取消</span>
          <button
            class="btn-confirm"
            native-type="submit"
            style="border: none; margin: 0; padding: 0"
          >
            提交
          </button>
        </div>
      </van-form>
    </div>
  </div>
</template>

<script>
import { Toast } from "vant";
import { mapGetters } from "vuex";
import {
  createSaCustomer,
  updateSaCustomer,
  getSaCustomer,
} from "@/api/member/saCustomer";
import { listSimpleUsers } from "@/api/system/user";
import { areaList } from "@vant/area-data";
export default {
  name: "MCustomerAdd",
  data() {
    return {
      showGroupList1: false,
      showGroupList2: false,
      showGroupList3: false,
      showGroupList4: false,
      ["showGroupList"]: false,
      userOptions: [],
      showArea: false,
      areaList, // 数据格式见 Area 组件文档
      value: "",
      formData: {
        id: undefined,
        customerId: undefined,
        companyName: undefined,
        customerSource: undefined,
        applicant: "",
        province: undefined,
        city: undefined,
        area: undefined,
        address: undefined,
        contactName: undefined,
        contactMobile: undefined,
        contactWx: undefined,
        contactTel: undefined,
        contactDepart: undefined,
        contactPost: undefined,
        status: undefined,
        remark: undefined,
        isValid: 0,
        contactList: [
          {
            preferredFlag: true
          },
        ],
      },
    };
  },
  computed: {
    ...mapGetters(["dict_datas", "getDictLabel", "areas", "roles", "userId"]),
    // 是否是客户归属人或者客户归属人主管
    isSalesStaff() {
      return !this.roles.find(e => e !== 'sales_staff' && e !== 'sales_supervisor')
    },
    customerSourceName(value) {
      if (this.formData.customerSource) {
        return this.getDictLabel(
          "customer_source",
          this.formData.customerSource
        );
      }
      return "";
    },
    isValidName() {
      if (this.formData.isValid) {
        return this.getDictLabel("customer_status", this.formData.isValid);
      }
      return "";
    },
    applicantName(value) {
      if (this.userOptions && this.userOptions.length) {
        const currentItem = this.userOptions.find(
          (e) => parseInt(e.id) === parseInt(this.formData.applicant)
        );
        return currentItem ? currentItem.nickname : id;
      }
      return "";
    },
    followUpStageName() {
      if (this.formData.followUpStage) {
        return this.getDictLabel(
          "follow_up_stage",
          this.formData.followUpStage
        );
      }
      return "";
    },
  },
  async created() {
    this.getSimpleUsers();
    this.formData.applicant = this.userId;
  },
  methods: {
    // 校验函数返回 true 表示校验通过，false 表示不通过
    validator(val) {
      return /1\d{10}/.test(val);
    },
    handleChangeGroup(value) {
      this[`showGroupList${value}`] = false;
    },
    handleDrop(value) {
      this[`showGroupList${value}`] = !this[`showGroupList${value}`];
    },
    async getSimpleUsers() {
      const res = await listSimpleUsers();
      this.userOptions = res.data || [];
    },
    onConfirm(values) {
      this.value = values
        .filter((item) => !!item)
        .map((item) => item.name)
        .join("/");
      if (values[2]) {
        this.formData.province = values[0].code;
        this.formData.city = values[1].code;
        this.formData.area = values[2].code;
      }

      this.showArea = false;
    },
    addContact() {
      if (this.formData.contactList.length >= 5) {
        Toast("联系人最多只能添加5个");
        return;
      }
      const isPreferredFlag = this.formData.contactList.find(
        (e) => e.preferredFlag
      );
      this.formData.contactList.push({ preferredFlag: !isPreferredFlag });
    },
    changeContactPreferredFlag(val, $index) {
      if (val) {
        this.formData.contactList.forEach((e, index) => {
          if (index !== $index) {
            e.preferredFlag = false;
          }
        });
      } else if (this.formData.contactList.length > 1) {
        this.formData.contactList[0].preferredFlag = true;
      }
    },
    onSubmit(values) {
      const formData = {
        ...this.formData,
      };
      // 添加的提交
      createSaCustomer(formData).then(({ data }) => {
        Toast("新增成功");
        this.$router.replace({ name: "MCustomer" });
      });
    },
    onClickLeft() {
      this.$router.go(-1);
    },
    cancel() {
      this.$router.go(-1);
    },
  },
};
</script>

<style lang="scss">
.contract-add-page {
  .van-field__error-message {
    text-align: right;
  }
  .top-fixed {
    position: fixed;
    width: 100%;
    z-index: 555;
  }
  .van-icon-plus {
    color: #999;
  }
  .pub-box {
    margin: 12px 0;
    border-radius: 6px;
    background-color: #fff;
    .req {
      color: #ee0a24;
      margin-right: 2px;
    }
    .pub-hd {
      height: 48px;
      overflow: hidden;
      display: flex;
      justify-content: center;
      align-items: center;
      padding: 0 12px;
      .pub-tit {
        font-size: 14px;
        color: #222;
        flex: 1;
      }
    }
    .pub-bd {
      padding: 12px;
      .pub-bd {
        color: #222;
        font-size: 14px;
      }
    }
  }
  .upload-area-box {
    .pub-tit {
      color: #666;
    }
    .pub-bd {
      font-size: 14px;
    }
    .li-row {
      display: flex;
      justify-content: center;
      align-items: center;
      .file-icon {
        background: url(../assets/image/addEdit/fileIcon.png);
        background-size: 100%;
        width: 24px;
        height: 24px;
      }
      .u-left {
        display: flex;
        flex: 1;
        align-items: center;
      }
      .u-right {
        img {
          width: 16px;
          height: 16px;
        }
      }
    }
  }
  .pro-list-box {
    .oop-ara {
      .b1 {
        width: 66px;
        height: 28px;
        background: #ebf2ff;
        border-radius: 4px 4px 4px 4px;
        line-height: 28px;
        overflow: hidden;
        text-align: center;
        color: #3875f6;
        border: none;
        margin: 0 4px 0 0;
      }
      .b2 {
        width: 110px;
        height: 28px;
        background: #3875f6;
        border-radius: 4px 4px 4px 4px;
        line-height: 28px;
        overflow: hidden;
        text-align: center;
        color: #3875f6;
        border: none;
        color: #fff;
      }
    }
  }
  .pub-table {
    overflow: hidden;
    border-radius: 4px;
    table {
      border-collapse: collapse;
      border: none;
      font-size: 12px;
      width: 100%;
      background: #f7faff;
    }
    th {
      background: #dfe5f3;
      text-align: left;
      padding: 8px;
    }
    td {
      color: #222;
      padding: 8px;
      text-align: left;
    }
    .tr1 {
      td {
        background: #f7faff;
      }
    }
    .tr2 {
      background: #dfe5f3;
    }
    input {
      width: 48px;
      height: 26px;
      border-radius: 2px 2px 2px 2px;
      border: 1px solid #3875f6;
      margin: 0;
      padding: 0;
      text-align: center;
      background: transparent;
    }
  }
  .more-form-area {
    padding: 50px 12px 12px 12px;
    .form-pub {
      border-radius: 6px 6px 6px 6px;
      background: #fff;
      overflow: hidden;
    }
  }
  .b-table {
    th {
      text-align: center;
    }
    td {
      text-align: center;
    }
  }
  .pub-btm-area {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    border-top: 1px solid #efefef;
    display: flex;
    height: 49px;
    line-height: 49px;
    background: #ffffff;
    .btn-reset {
      text-align: center;
      flex: 1;
      font-size: 16px;
      color: #3875f6;
      cursor: pointer;
    }
    .btn-confirm {
      text-align: center;
      font-size: 16px;
      color: #fff;
      background: #3875f6;
      flex: 1;
      cursor: pointer;
    }
  }
}
</style>
